/**
 * Project Name:fastPlat
 * File Name:PermissionController.java
 * Package Name:com.fast.cms.web.controller.admin
 * Date:2014年12月17日下午3:07:00
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 */
package com.fast.user.web.controller.admin;

import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fast.base.cache.MemcachedUtils;
import com.fast.base.model.AnoSysLog;
import com.fast.base.model.TreeModel;
import com.fast.base.security.StringEncrypt;
import com.fast.base.util.LogUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.web.BaseController;
import com.fast.common.CacheConstant;
import com.fast.common.userCache.AdminCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.admin.Permission;
import com.fast.user.service.admin.PermissionService;

/**
 * ClassName:PermissionController <br/>
 * 用途:权限控制  <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2014年12月17日 下午3:07:00 <br/>
 */
@Controller
@RequestMapping("/permission")
public class PermissionController extends BaseController{
	
	
	@Resource(name="permissionService")
	private PermissionService permissionService;
	
	
	/**
	 * 说明: 顺序调整成功 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年10月12日 下午10:55:09 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping("/setOrderVal.do")
	public ResponseData setOrderVal(String setType,int id){
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = this.permissionService.setOrderVal(setType,id);
			if(actionFlag){
				responseData.setMsg("顺序调整成功！");
			}else{
				responseData.failue();
			}
		} catch (Exception e) {
			LogUtils.error("copyPermission err:", e);
			e.printStackTrace();
		}
		return responseData;
	} 
	
	/**
	 * 拷贝权限
	 * @param toPermissitonId
	 * @param uuidArray
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/copyPermission.do")
	public ResponseData copyPermission(String toPermissitonId,String uuidArray){
		ResponseData responseData = new ResponseData();
		try {
			if(StringUtils.isEmpty(toPermissitonId)){
				responseData.setCode("01");
				responseData.setMsg("拷贝的目标权限不能为空");
				return responseData;
			}
			
			if(StringUtils.isEmpty(uuidArray)){
				responseData.setCode("01");
				responseData.setMsg("请选择要拷贝的权限！");
				return responseData;
			}
			boolean actionFlag = this.permissionService.copyPermission(toPermissitonId,uuidArray);
			if(!actionFlag){
		         responseData.failue();
			}
			//清除缓存
			List<String> keyList = MemcachedUtils.getAllKeys();
			for (String key : keyList) {
				if(key.startsWith(CacheConstant.SYSTEM_CODE)) {
					MemcachedUtils.delete(key);
				}
			}
		} catch (Exception e) {
			LogUtils.error("copyPermission err:", e);
			e.printStackTrace();
		}
		return responseData;
	} 
 	
	
	/**
	 * 获取权限信息
	 * @param formData
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPmsSource.do")
	public JSONArray getPmsSource(String parentUUID){
		AdminUser adminUser = AdminCacheUtils.getLoginAdminUser();
		String pmsArr = UserRequestUtils.getCurPmsArray();
		//默认只挖一级
		int depth = webUtil.getInt("depth",1);
		if(adminUser!=null){
			//如果是开发人员将不进行权限控制
			if(adminUser.getGroupName().equals("开发人员")){
				pmsArr = "all";
			}
		}
		JSONArray jsonArray = new JSONArray();
		String cacheKey = StringEncrypt.SHA256(CacheConstant.SYSTEM_CODE+parentUUID+"_"+pmsArr+"_"+depth);
		if (MemcachedUtils.getCachedClient().keyExists(cacheKey)) {
			jsonArray = (JSONArray) MemcachedUtils.get(cacheKey);
			LogUtils.info("getPmsSource get memcache data!");
		}else {
			jsonArray = this.permissionService.getTreeForJsonArray(parentUUID,pmsArr,depth);
			MemcachedUtils.set(cacheKey, jsonArray, 60*10);
		}
		return jsonArray;
	}


	/**
	 * 编辑[权限动作]信息
	 * @param formData
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editPermission.do")
	@AnoSysLog(actionName="编辑[权限动作]信息")
	public ResponseData editPermission(String formData) {
		LogUtils.info("editPermission_param:"+formData);
		Permission permission = (Permission) JSON.parseObject(formData.replace("&quot;", "\'"),Permission.class);;
		ResponseData responseData = new ResponseData();
		try {
			//不存在UUID时的处理
			if(StringUtils.isBlank(permission.getUuid())){
				permission.setUuid(MathUtils.getTheOnlyStr());
				UserRequestUtils.bindCreaterInfo(permission);
			}else{
				UserRequestUtils.bindEditorInfo(permission);
			}
			boolean actionFlag = permissionService.saveOrUpdatePermission(permission);
			if(actionFlag){
				//清除缓存
				List<String> keyList = MemcachedUtils.getAllKeys();
				for (String key : keyList) {
					if(key.startsWith(CacheConstant.SYSTEM_CODE)) {
						MemcachedUtils.delete(key);
					}
				}
				responseData.setMsg("操作成功");
			}
			responseData.setCode(actionFlag?"00":"01");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		LogUtils.info("editPermission_result:"+responseData);
		return responseData;
	}

	/**
	 * 批量编辑[权限动作]信息
	 * @param formData
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editAllPermission.do")
	@AnoSysLog(actionName="批量编辑[权限动作]信息")
	public ResponseData editAllPermission(String formData) {
		LogUtils.info("editAllPermission_param:"+formData);
		List<Permission> psmList = JSONArray.parseArray(formData.replace("&quot;", "\'"), Permission.class);
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = psmList.size();
			int success     = 0;
			int failure     = 0;
			for (Permission permission : psmList) {
				//设计唯一UUID
				permission.setUuid(MathUtils.getTheOnlyStr());
				//设置权限编码
				String psmCode = permissionService.genPsmCode(permission);
				permission.setPsmCode(psmCode);
				permission.setGrade(permissionService.genPsmGrade(permission));
				permission.setOrderNo(permissionService.genOrderNo(permission));
				//设置操作人编辑人
				UserRequestUtils.bindCreaterInfo(permission);
				UserRequestUtils.bindEditorInfo(permission);
				boolean actionFlag = permissionService.saveOrUpdatePermission(permission);
				Thread.sleep(50);
				if(actionFlag){
					success++;
				}else{
					failure++;
				}
			}
			//清除缓存
			List<String> keyList = MemcachedUtils.getAllKeys();
			for (String key : keyList) {
				if(key.startsWith(CacheConstant.SYSTEM_CODE)) {
					MemcachedUtils.delete(key);
				}
			}
		    responseData.setMsg("批量操作结果为：共添加数据["+actionCount+"],成功保存["+success+"],失败保存["+failure+"]");
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setMsg("批量保存数据失败！");
		}
		LogUtils.info("editAllPermission_result:"+responseData);
		return responseData;
	}
	

	/**
	 * 得到全部[权限动作]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonAllList.do")
	public ResponseData getPermissionAllList() {
		ResponseData responseData = new ResponseData();
		List<Permission> beanList = permissionService.queryForBeanList(Permission.class, " order by id desc");
		try {
			responseData.setCode("00");
			responseData.setData(beanList);
			responseData.setMsg("获取信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("获取信息失败");
		}
		return responseData;
	}
	
	/**
	 * 得到全部[权限动作]信息,用于树结构
	 * @param id
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/getTreeJsonList.do")
	public JSONArray getPermissionTreeList(String parentUUID) throws IOException {
		if(parentUUID.equals("")){
			parentUUID = "0";
		}
		List<Permission> pmsList =  permissionService.queryForBeanList(Permission.class, " where parentUUID='"+parentUUID+"' order by orderNo asc");
		JSONArray jsonArray = new JSONArray();
		TreeModel treeModel = null;
		for (Permission pms : pmsList) {
			treeModel = new TreeModel();
			treeModel.setLabel(pms.getPsmName());
			treeModel.setValue(pms.getPsmName());
			treeModel.setId(pms.getUuid());
			treeModel.setIcon(webUtil.getBasePath()+"admin/images/card.png");
			//判断是否还有下一级
			boolean exist = permissionService.isExist(Permission.class, " where parentUUID='"+pms.getUuid()+"'");
			if(exist){
				treeModel.setIcon(webUtil.getBasePath()+"admin/images/folder.png");
				TreeModel child = new TreeModel(webUtil.getBasePath()+"PermissionController/getTreeJsonList.do?parentUUID="+pms.getUuid(),"加载中...");
				child.setIcon(webUtil.getBasePath()+"admin/images/loading1616.gif");
				List<TreeModel> list = new ArrayList<TreeModel>();
				list.add(child);
				treeModel.setItems(list);
			}
			jsonArray.add(JSONObject.toJSON(treeModel));
		}
		return jsonArray;
	}
	
	/**
	 * 删除[权限动作]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delPermission.do")
	@AnoSysLog(actionName="删除权限信息")
	public ResponseData delPermission(int id) {
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = permissionService.deleteById(Permission.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.setMsg("删除部门编号为["+id+"]操作成功");
			}else{
				responseData.setMsg("删除部门编号为["+id+"]操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除部门编号为["+id+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 删除多个[权限动作]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMorePermission.do")
	@AnoSysLog(actionName="批量删除权限信息")
	public ResponseData delMorePermission(String ids) {
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = permissionService.deleteByIds(Permission.class, ids);
			responseData.setCode("00");
			responseData.setMsg("删除[权限动作]编号为["+ids+"]操作成功,共成功["+actionCount+"]");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除[权限动作]["+ids+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 得到[权限动作]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonDetail.do")
	public ResponseData getPermissionDetail(int id) {
		ResponseData responseData = new ResponseData();
		Permission bean = permissionService.queryForBeanById(Permission.class, id);
		try {
			responseData.setCode("00");
			responseData.setData(bean);
			responseData.setMsg("获取信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("获取信息失败");
		}
		return responseData;
	}
	
	
	
	
	/**
	 * 标题：getPermissionList4Tree <br/>
	 * 作用：得到数据字典     <br/>
	 * @author developer-lushuifa
	 * @throws Exception
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/getPermissionList4Tree.do")
	public JSONArray getPermissionList4Tree(){
		String parentUUID = webUtil.getString("id");
		boolean isRoot = false;
		if(parentUUID.equals("")){
			parentUUID="0";
			if(!webUtil.getString("parentUUID").equals("")){
				parentUUID=webUtil.getString("parentUUID");
				isRoot = true;
			}
		}
		JSONArray rootJo = this.permissionService.getPermissionTreeData(parentUUID,isRoot);
		System.out.println(rootJo.toString());
		return rootJo;
	}
	
	/**
	 * 得到[权限动作]列表，treegrid
	 * @param dtGridPager Pager对象
	 * @param request  请求对象
	 * @param response 响应对象
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getPermissionList4treeGrid.do", method=RequestMethod.POST)
	public JSONArray getPermissionList4treeGrid(){
		String parentUUID = webUtil.getString("id");
		if(parentUUID.equals("")){
			parentUUID="0";
		}
		JSONArray rootJo = this.permissionService.getTreeGridData(parentUUID);
		return rootJo;
	}
	
	/**
	 * 得到[权限动作]列表，treegrid
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getPermissionTree.do", method=RequestMethod.POST)
	public Object getPermissionTree(@RequestParam(value="id",defaultValue="0") String parentUUID,
			@RequestParam(value="groupUUID",required = false) String groupUUID
			){
		String permissionArray = "";
		if(StringUtils.isNotEmpty(groupUUID)){
			permissionArray = this.permissionService.getPermissionArray(groupUUID);
		}
		String userUUID = AdminCacheUtils.getLoginAdminUser().getUuid();
		String cacheKey = CacheConstant.getPermissionTreeKey(userUUID+"_"+ parentUUID+"_"+groupUUID);
		boolean cacheFlag = MemcachedUtils.getCachedClient().keyExists(cacheKey);
		JSONArray rootJo = new JSONArray();
		if(cacheFlag) {
			rootJo = (JSONArray) MemcachedUtils.get(cacheKey);
			LogUtils.info("getPermissionTree cache data!");
		}else {
			rootJo = this.permissionService.getPsmTreeData(parentUUID,permissionArray,cacheKey);
			MemcachedUtils.add(cacheKey, rootJo, 60*30);
		}
		LogUtils.info("getPermissionTree result:"+rootJo.toString());
		return rootJo;
	}
}

